package com.tiut.lmap.controller;

import com.tiut.lmap.common.ErrorCode;
import com.tiut.lmap.exception.ThrowUtils;
import com.tiut.lmap.model.pojo.Chat;
import com.tiut.lmap.model.vo.MessageVo;
import com.tiut.lmap.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/ai")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private ChatService chatService;
    @Autowired
    private ChatMemory chatMemory;
    @Autowired
    private RedisTemplate redisTemplate;

    //    @GetMapping("/chat")
//    //阻塞式
//    public String chat( String prompt) {
//        return chatClient
//                .prompt()
//                .user(prompt)// 传入user提示词
//                .call() // 同步请求，会等待AI全部输出完才返回结果
//                .content(); //返回响应内容
//    }

    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    //流式 produces保证得到的结果不会乱码
    public Flux<String> chat(String prompt, String chatId) {
        //判空
        ThrowUtils.throwIf(StringUtils.isEmpty(chatId), ErrorCode.PARAMS_ERROR, "id为空");
        //请求
        Flux<String> content = chatClient
                .prompt()
                .user(prompt)// 传入user提示词
                .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream() // 同步请求，会等待AI全部输出完才返回结果
                .content();

        return content; //返回响应内容
    }


    /**
     * 根据业务类型获取ids
     *
     * @param type
     * @return
     */
    @GetMapping("/history/{type}")
    public Set<String> getChatIds(@PathVariable("type") String type) {
        //判空
        ThrowUtils.throwIf(StringUtils.isEmpty(type), ErrorCode.PARAMS_ERROR, "type为空");
        //在缓存中获取，如果没有查询数据库
        Set<String> members = redisTemplate.opsForSet().members(type);
        if (members.size()==0) {
            Set<String> chatIds = chatService.getChatIds(type);
            redisTemplate.opsForSet().add(type, chatIds.toArray());
        }

        return redisTemplate.opsForSet().members(type);
    }

    /**
     * 根据业务类型、chatId查询会话历史
     *
     * @param type   业务类型，如：chat,service,pdf
     * @param chatId 会话id
     * @return 指定会话的历史消息
     */
    @GetMapping("/history/{type}/{chatId}")
    public List<MessageVo> getChatHistory(@PathVariable("type") String type, @PathVariable("chatId") String chatId) {
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isEmpty(chatId), ErrorCode.PARAMS_ERROR, "id为空");
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (messages == null) {
            return List.of(); // 返回空列表
        }
        // 将消息列表转换为 MessageVo 并返回
        return messages.stream().map(MessageVo::new).collect(Collectors.toList());
    }
}




